<template>
  <el-dialog :title="mode === 'add' ? '添加用户' : '编辑用户'" v-model="dialogVisible" width="500px" destroy-on-close>
    <el-form :model="form" :rules="rules" ref="formRef" label-width="80px">
      <el-form-item label="姓名" prop="userName">
        <el-input v-model="form.userName" />
      </el-form-item>
      <el-form-item label="账号" prop="loginName">
        <el-input v-model="form.loginName" />
      </el-form-item>
      <el-form-item label="职位" prop="roleId">
        <el-select v-model="form.roleId" placeholder="请选择">
          <el-option label="管理员" :value="100" />
          <el-option label="医生" :value="102" />
          <el-option label="客服" :value="103" />
        </el-select>

      </el-form-item>
      <el-form-item label="邮箱" prop="email">
        <el-input v-model="form.email" />
      </el-form-item>
      <el-form-item label="电话" prop="phoneNumber">
        <el-input v-model="form.phoneNumber" />
      </el-form-item>
      <el-form-item label="性别" prop="sex">
        <el-radio-group v-model="form.sex">
          <el-radio :value="'0'">男</el-radio>
          <el-radio :value="'1'">女</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-segmented v-model="form.status" :options="[
          { label: '正常', value: '0' },
          { label: '停用', value: '1' }
        ]" />
      </el-form-item>
      <el-form-item label="密码" prop="password">
        <el-input v-model="form.password" type="password" show-password placeholder="请输入密码（留空则不修改）" />
      </el-form-item>
      <el-form-item label="确认密码" prop="confirmPassword">
        <el-input v-model="form.confirmPassword" type="password" show-password placeholder="请再次输入密码" />
      </el-form-item>
      <el-form-item label="备注">
        <el-input v-model="form.remark" type="textarea" />
      </el-form-item>
    </el-form>

    <template #footer>
      <el-button @click="dialogVisible = false">取消</el-button>
      <el-button type="primary" @click="handleSubmit">
        {{ mode === 'add' ? '确认添加' : '保存修改' }}
      </el-button>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, watch } from 'vue'
import { ElMessage } from 'element-plus'
import { updateUser, register } from '@/api/user' // 假设有一个更新用户的API
// import { addUserApi, updateUserApi } from '@/api/user'

const props = defineProps({
  visible: Boolean,
  mode: String,
  user: Object
})

const emit = defineEmits(['update:visible', 'refresh'])

const dialogVisible = ref(false)
watch(() => props.visible, val => dialogVisible.value = val)
watch(() => dialogVisible.value, val => emit('update:visible', val))

const formRef = ref()
const form = ref({
  userName: '',
  loginName: '',
  roleId: '',
  email: '',
  phoneNumber: '',
  sex: '0',
  status: '0',
  password: '',
  confirmPassword: '',
  remark: ''
})

watch(() => props.user, (val) => {
  if (props.mode === 'edit' && val) {
    form.value = {
      ...val,
      password: '',
      confirmPassword: ''
    }
  } else {
    resetForm()
  }
})

const rules = {
  userName: [{ required: true, message: '请输入姓名', trigger: 'blur' }],
  loginName: [{ required: true, message: '请输入账号', trigger: 'blur' }],
  roleId: [{ required: true, message: '请选择职位', trigger: 'change' }],
  phoneNumber: [{ required: true, message: '请输入电话', trigger: 'blur' }],
  password: [
    {
      validator: (rule, value, callback) => {
        if (value && value.length < 6) {
          callback(new Error('密码至少6位'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ],
  confirmPassword: [
    {
      validator: (rule, value, callback) => {
        if (form.value.password && value !== form.value.password) {
          callback(new Error('两次输入密码不一致'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ]
}

const resetForm = () => {
  form.value = {
    userName: '',
    loginName: '',
    roleId: '',
    email: '',
    phoneNumber: '',
    sex: '0',
    status: '0',
    password: '',
    confirmPassword: '',
    remark: ''
  }
}

const handleSubmit = () => {
  formRef.value.validate(async valid => {
    if (!valid) return

    const payload = { ...form.value }
    if (!payload.password) {
      delete payload.password
    }

    delete payload.confirmPassword

    if (props.mode === 'add') {
      // await addUserApi(payload)
      console.log('添加用户:', payload);
      await register(payload)
        .then(() => {
          ElMessage.success('用户添加成功')
        })
        .catch(err => {
          ElMessage.error('用户添加失败: ' + err.message)
        })
    } else {
      // await updateUserApi(payload)
      console.log('更新用户:', payload);
      // 这里可以添加更新用户的逻辑
      await updateUser(payload)
        .then(() => {
          ElMessage.success('用户信息更新成功')
        })
    }

    dialogVisible.value = false
    emit('refresh')
  })
}
</script>
